# coding: utf-8

from leancloud import Object
from leancloud import File
from leancloud import Query
from leancloud import LeanCloudError
from leancloud import User
from flask import request
from datetime import datetime
import time
import os
from werkzeug.utils import secure_filename
import json


class FarmerSayItem(Object):
    pass


class FavoriteSay():
    def __init__(self):
        pass

    # 赞说说
    def like(self):
        name = request.json['name']
        objectId = request.json['objectId']
        try:
            query = Query(FarmerSayItem)
            farmerSayItem = query.get(objectId)
        except LeanCloudError, e:
            if e.code == 101:  # 服务端对应的 Class 还没创建
                farmerSayItem = None
            else:
                raise e

        favorterStr = farmerSayItem.get('favorters')
        if favorterStr == None:
            favorters = []
        else:
            favorters = eval(favorterStr)
        url = None
        try:
            mUsers = Query(User).equal_to("username", name).descending(
                    'createdAt').find()
            count = len(mUsers)
            if (count > 0):
                fil = mUsers[0].get('avatar')
                if (fil != None):
                    url = fil.url
                else:
                    url = None
        except LeanCloudError, e:
            url = None
            if e.code == 101:  # 服务端对应的 Class 还没创建
                mUsers = []
            else:
                raise e

        favorter = {}
        favorter['name'] = name
        favorter['avatar'] = url
        favorter['time'] = long(time.time() * 1000)
        favorters.append(favorter)
        farmerSayItem.set('favorters', str(favorters))
        farmerSayItem.save()

        data = {'code': 200, "state": "success"}
        return json.dumps(data, indent=1)
        pass

        # 取消赞说说

    def unLike(self):
        name = request.json['name']
        objectId = request.json['objectId']
        try:
            query = Query(FarmerSayItem)
            farmerSayItem = query.get(objectId)
        except LeanCloudError, e:
            if e.code == 101:  # 服务端对应的 Class 还没创建
                farmerSayItem = None
            else:
                raise e

        favorterStr = farmerSayItem.get('favorters')
        if favorterStr == None:
            favorters = []
        else:
            favorters = eval(favorterStr)
        count = 0
        for favorter in favorters:
            print "########################"
            print favorter.get('name')
            if favorter.get('name') == name:
                favorters.remove(favorter)
                farmerSayItem.set('favorters',str(favorters))
                farmerSayItem.save()
            count += 1
        data = {'code': 200, "state": "success"}
        return json.dumps(data, indent=1)
        pass
